package xin.marcher.module.diplomacy.mq.consumer.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.enums.message.BinlogType;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.diplomacy.api.TableDataUpdateApi;
import xin.marcher.module.diplomacy.domain.dto.TableDataChangeDTO;

import java.util.List;

/**
 * 处理商品变更的缓存处理
 */
@Slf4j
@Component
public class ProductUpdateListener implements MessageListenerConcurrently {

    @DubboReference(version = "1.0.0")
    private TableDataUpdateApi tableDataUpdateApi;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                // 消息处理这里，涉及到sku的缓存更新以及对应的整个商品明细的缓存更新
                String msg = new String(messageExt.getBody());
                log.info("执行商品缓存数据更新逻辑，消息内容：{}", msg);

                TableDataChangeDTO tableDataChangeMessage = JsonUtil.json2Object(msg, TableDataChangeDTO.class);
                if (BinlogType.INSERT.getValue().equals(JSON.parseObject(msg).get("action"))) {
                    // 新增，需要将数据添加至布隆过滤器
                    tableDataUpdateApi.addBloomFilter(tableDataChangeMessage);
                }

                // 更新sku对应的商品缓存信息
                tableDataUpdateApi.tableDataChange(tableDataChangeMessage);

                tableDataUpdateApi.sendCallbackMessage(tableDataChangeMessage);
            }
        } catch (Exception e) {
            log.error("consume error, 商品缓存更新失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
